const fs = require('fs'),
log = require('./log'),
oldPath = 'D:\\Program Files\\nodejs\\work\\xyb\\bak\\5.0',
newPath = 'D:\\Program Files\\nodejs\\work\\xyb\\bak\\5.1',
targetPath = 'D:\\Program Files\\nodejs\\work\\xyb\\bak\\update',
separator = '\\';

function findDifferentFiles(path, resolve) {
	fs.readdir(path, (err, list) => {
		if (err)
			throw err;
		var promiseList = []
		list.forEach(item => {
			promiseList.push(new Promise(resolve => {
					var _path = path + separator + item;
					fs.stat(_path, (err, stats) => {
						if (err)
							throw err;
						if (stats.isDirectory())
							findDifferentFiles(_path, resolve);
						else {
							fs.exists(oldPath + _path.substring(newPath.length), exists => {
								if (exists)
									resolve();
								else {
									new Promise(resolve => {
										var __path = targetPath + _path.substring(newPath.length);
										__path = __path.substring(0, __path.lastIndexOf(separator));
										fs.exists(__path, exists => {
											if (exists)
												resolve();
											else
												mkdir(__path, resolve)
										})
									}).then(() => {
										fs.readFile(_path, (err, data) => {
											if (err)
												throw err;
											fs.writeFile(targetPath + _path.substring(newPath.length), data, err => {
												if (err)
													throw err;
												resolve()
											})
										})
									}).catch (err => {
										console.log(err)
									})
								}
							})
						}
					})
				}))
		})
		Promise.all(promiseList).then(() => {
			resolve()
		}).catch (err => {
			console.log(err)
		})
	})
}

function mkdir(path, resolve) {
	fs.exists(path, exists => {
		if (exists)
			resolve();
		else
			mkdir(path.substring(0, path.lastIndexOf(separator)), () => {
				fs.mkdir(path, err => {
					if (err) {
						if (err.code != 'EEXIST') {
							log(err.code)
							throw err
						}
					}
					resolve()
				})
			})
	})
}

function deleteTargetFiles(path, resolve) {
	fs.readdir(path, (err, list) => {
		if (err)
			throw err;
		var promiseList = []
		list.forEach(item => {
			promiseList.push(new Promise(resolve => {
					var _path = path + separator + item;
					fs.stat(_path, (err, stats) => {
						if (err)
							throw err;
						if (stats.isDirectory())
							deleteTargetFiles(_path, () => {
								fs.rmdir(_path, () => {
									resolve()
								})
							});
						else {
							fs.unlink(_path, () => {
								resolve()
							})
						}
					})
				}))
		})
		Promise.all(promiseList).then(() => {
			resolve()
		})
	})
}

deleteTargetFiles(targetPath, () => {
	findDifferentFiles(newPath, () => {
		fs.readFile(newPath + separator + 'index.html', (err, data) => {
			if (err)
				throw err;
			fs.writeFile(targetPath + separator + 'index.html', data, err => {
				if (err)
					throw err;
			})
		})
	})
})
